# coding=utf-8
"""
作者：董新强 
创建时间：
描述：
"""
import os
import re

import xlrd

from db_models.raw_questions import RawQuestions
from framework.db_session import DbSession
from framework.utilities import to_string

question_pattern = re.compile('^\d+[．.、]')
options_pattern = re.compile('^[ABCD][．.、,，：:]?')


def read_from_excel(directory, file_name):
    '''                                                  \
    解析excel为数组列表
    :param file_name:excel的名称
    :type file_name:
    :return: excel行的数组
    :rtype:list
    '''
    values = []
    try:
        workbook = xlrd.open_workbook(os.path.join(directory, file_name))
        sheet_name = workbook.sheet_names()[0]
        sheet = workbook.sheet_by_name(sheet_name)
        values = sheet._cell_values
    except Exception as e:
        print(e)
    return values


def save_to_raw(fname, dim):
    rows = read_from_excel('D:\\Wechat\\WeChat Files\\wxid_11twyf7wc8zt51\\FileStorage\\File\\2020-08', fname)
    question_ls = []
    for idx, row in enumerate(rows):
        if not idx:
            continue
        title = question_pattern.sub('', row[0])
        a = options_pattern.sub('', row[1])
        b = options_pattern.sub('', row[2])
        c = options_pattern.sub('', row[3])
        d = options_pattern.sub('', row[4])
        anwer = row[5].strip()

        rq = RawQuestions()
        rq.title = title
        rq.options = to_string([{"id": "a", "name": a}, {"id": "b", "name": b}, {"id": "c", "name": c}, {"id": "d", "name": d}])
        rq.answer = anwer.lower()
        rq.dim = dim
        rq.b = 3.0
        question_ls.append(rq)

    with DbSession.create() as db:
        db.bulk_save_objects(question_ls)


if __name__ == '__main__':
    fname = '习题2.xlsx'
    save_to_raw(fname, dim='psyc2')
